package rdd.operate;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Int;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Spark55_Operate_mapValues {
    public static void main(String[] args) {
        final SparkConf conf = new SparkConf();
        conf.setMaster("local");
        conf.setAppName("spark");
        final JavaSparkContext jsc = new JavaSparkContext(conf);

        final List<Integer> nums = Arrays.asList(1,2,3,4);
        final JavaRDD<Integer> rdd = jsc.parallelize(nums);
        //因为groupBy生成的是kv类型，所以需要用JavaPairRDD接受，不能用JavaRDD
        final JavaPairRDD<Integer,Iterable<Integer>> grouprdd = rdd.groupBy(
                num -> num % 2                                                          //生成的是（0，[2,4]）  （1，[1，3]）
        );
        grouprdd.mapValues(
                itera -> {
                    int num = 0;
                    Iterator<Integer> iterator = itera.iterator();
                    while(iterator.hasNext()){
                        num =num + iterator.next();
                    }
                    return num;
                }
        ).collect().forEach(System.out::println);
        jsc.close();
    }
}
